/* eslint-disable react/sort-comp */
import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Divider,
  Input,
  Row,
  Select,
  Cascader,
  Modal,
  Badge,
  Tooltip,
  Dropdown,
  Menu,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';


const { Item } = Form;
const { Option } = Select;
const { pathname } = window.location;

type IStatusMapType = '' | 'success' | 'default';
const statusMap = ['', 'success', 'default'];
const status = ['', '上线', '下线'];

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  partnerFranchiseeList: any;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
}

interface TableListState {
  offlineDialog: boolean;
  fId: number;
  current: number;
  pageSize: number | undefined;
  formValues: any;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(({
  partnerFranchiseeList,
  common: { INITINFO },
  global: { screen, hasPath },
  loading,
}: any) => ({
  partnerFranchiseeList,
  INITINFO,
  screen,
  hasPath,
  loading: loading.effects['partnerFranchiseeList/fetch'],
}))
class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: '合作商名称',
      dataIndex: 'name',
      width: 120,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowFranchisee(record.id, text)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '级别',
      dataIndex: 'level',
      width: 60,
    },
    {
      title: '联系人',
      dataIndex: 'contact',
      width: 80,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '联系人电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '授权区域',
      dataIndex: ['region_info', 'area'],
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
          >
            {text || '--'}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '独家',
      dataIndex: ['region_info', 'is_exclusive'],
      width: 60,
      render: (text: number) => (text ? '是' : '否'),
    },
    {
      title: '创建人',
      dataIndex: 'create_user',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      width: 140,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render(text: IStatusMapType) {
        return <Badge status={statusMap[text]} text={status[text]} />;
      },
    },
    {
      title: '操作',
      width: 120,
      fixed: 'right',
      dataIndex: 'id',
      render: (id: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleShowFranchisee(id, record.name)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleEditFranchisee(id, record.name)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={this.menu(record)} trigger={['click']}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </div>
      ),
    },
  ];

  state: TableListState = {
    fId: 0,
    current: 1,
    pageSize: 20,
    formValues: {},
    offlineDialog: false,
    rowId: 0,
  };

  menu = (record: any) => (
    <Menu>
      <Menu.Item
        className="operLink"
        onClick={() => this.handleShowOfflineDialog(record.id)}
      >
        下线
      </Menu.Item>
      <Menu.Item
        className="operLink"
        onClick={() => this.handlePushFranchisee(record.id, record.name)}
      >
        配置
      </Menu.Item>
    </Menu>
  )


  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { partnerFranchiseeList: { data }, hasPath } = this.props;
    if (data?.list?.length && !hasPath) return;

    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchFranchiseeList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchFranchiseeList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const { formValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(formValues);
  }

  // 获取数据
  fetchFranchiseeList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchAddressList' });
    dispatch({
      type: 'partnerFranchiseeList/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const {
      formValues: { area_code, ...params },
      current,
      pageSize,
    } = this.state;

    if (area_code && area_code.length) {
      [params['org1.area_code'], params['org2.area_code'], params['org3.area_code']] = area_code;
    }
    params.pageNum = current;
    params.numPerPage = pageSize;

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '合作商',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleFormReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 添加合作商
   */
  handleAddFranchisee = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '添加合作商',
      url: '/partner/franchisee/list/add',
    });
  };

  /**
   * 编辑合作商
   */
  handleEditFranchisee = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/partner/franchisee/list/edit?id=${id}`,
    });
  };

  /**
   * 查看合作商
   */
  handleShowFranchisee = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/partner/franchisee/list/detail?id=${id}`,
    });
  };

  /**
   * 推送配置
   */
  handlePushFranchisee = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `/partner/franchisee/list/push/${id}`,
    });
  };

  /**
   * 打开下线提示框
   */
  handleShowOfflineDialog = (fId: number) => this.setState({ fId, offlineDialog: true });

  /**
   * 确定下线提示
   */
  handleConfirmOffline = () => {
    this.handleHideOfflineDialog();

    const { fId: id } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'partnerFranchiseeList/offline',
      payload: {
        ...this.getQueryParams(),
        id,
      },
    });
  };

  /**
   * 关闭下线提示框
   */
  handleHideOfflineDialog = () => this.setState({ offlineDialog: false });

  // 分页
  onSelectChange = (page: number, psize: number | undefined) => {
    const { formValues } = this.state;
    const query = { ...formValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '合作商',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem() {
    const {
      form: { getFieldDecorator },
      INITINFO: { addressList },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} colon={false} className="tableListForm">
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="合作商名称">
              {getFieldDecorator('name')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={5} sm={24}>
            <Item label="授权区域">
              {getFieldDecorator('area_code')(
                <Cascader
                  changeOnSelect
                  options={addressList}
                  placeholder="请选择"
                />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="联系人电话">
              {getFieldDecorator('phone')(
                <Input
                  allowClear
                  type="number"
                  placeholder="请输入"
                  style={{ width: '100%' }}
                />,
              )}
            </Item>
          </Col>
          <Col md={4} sm={24}>
            <Item label="是否独家">
              {getFieldDecorator('is_exclusive')(
                <Select placeholder="请选择" allowClear>
                  <Option value="0">非独家</Option>
                  <Option value="1">独家</Option>
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={3} sm={24}>
            <div className="flexFeView">
              <Button type="primary" htmlType="submit" className="smallButton">
                查询
              </Button>
              <Button
                className="addButton smallButton marginL16"
                type="primary"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      current,
      pageSize,
      offlineDialog,
    } = this.state;

    const {
      partnerFranchiseeList: { data },
      screen,
      loading,
    } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${data.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddFranchisee}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="确认提示"
          style={{ top: 200 }}
          visible={offlineDialog}
          onOk={this.handleConfirmOffline}
          onCancel={this.handleHideOfflineDialog}
        >
          <p>您确定要将此合作商下线吗？</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
